import React from "react";
import PropTypes from "prop-types";
import ReactMarkdown from 'react-markdown';
import { Button, message, Modal, Space } from 'antd';
import { 
  SoundOutlined, 
  CopyOutlined, 
  RedoOutlined, 
  ShareAltOutlined,
  MoreOutlined 
} from '@ant-design/icons';
import { useGlobalContext } from "../../context/GlobalContext";
import { getApiUrl } from "../../config/api";
import Avatar from "../../assets/avatar.png";
import IconEdit from "../../assets/edit.svg";
import IconRightBottomArrow from "../../assets/right-bottom-arrow.svg";
import "./index.css";

export const ChatItem = (props) => {
  const { chatContent } = props;
  const { setChatContent } = useGlobalContext();
  const messages = Array.isArray(chatContent) ? chatContent : [{ role: 'assistant', content: chatContent }];
  const [isPlaying, setIsPlaying] = React.useState(false);

  const handleVoicePlay = (content) => {
    try {
      if (isPlaying) {
        
        window.speechSynthesis.cancel();
        setIsPlaying(false);
        message.info('已停止语音播放');
        return;
      }

      // 创建语音合成实例
      const speech = new SpeechSynthesisUtterance();
      speech.text = content;
      speech.lang = 'zh-CN';
      speech.rate = 1;
      speech.pitch = 1;
      speech.volume = 1;
      
      // 播放出错时的回调
      speech.onerror = (event) => {
        // 只有在非主动取消的情况下才显示错误信息
        if (isPlaying) {
          setIsPlaying(false);
          console.error('语音播放失败:', event);
          message.error('语音播放失败');
        }
      };
      
      // 开始播放
      window.speechSynthesis.speak(speech);
      setIsPlaying(true);
      
      // 播放完成时的回调
      speech.onend = () => {
        setIsPlaying(false);
        message.success('播放完成');
      };

    } catch (error) {
      setIsPlaying(false);
      console.error('语音播放失败:', error);
      message.error('语音播放失败');
    }
  };

  const handleCopy = async (content) => {
    try {
      await navigator.clipboard.writeText(content);
      message.success('复制成功');
    } catch (err) {
      message.error('复制失败');
    }
  };

  const handleRegenerate = async (content, index) => {
    try {
      // 找到当前 AI 回答对应的用户问题
      const userQuestion = messages[index - 1]?.content;
      if (!userQuestion) {
        message.error('找不到对应的问题');
        return;
      }

      const token = localStorage.getItem('token');
      const cleanToken = token.replace(/['"]+/g, '');

      // 使用原问题获取新的 AI 回答
      const aiResponse = await fetch(getApiUrl('/api/chat/query'), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${cleanToken}`,
          "x-regenerate": "true",
        },
        body: JSON.stringify({ prompt: userQuestion }),
      });

      const aiData = await aiResponse.json();
      if (!aiData.ok) {
        throw new Error("重新生成回答失败");
      }

      // 只更新当前 AI 回答
      const newMessages = [...messages];
      newMessages[index] = { ...messages[index], content: aiData.data };
      setChatContent(newMessages);
      message.success('重新生成成功');
    } catch (error) {
      console.error("重新生成失败:", error);
      message.error('重新生成失败');
    }
  };

  const handleShare = async (content) => {
    Modal.confirm({
      title: '分享对话',
      width: 400,
      icon: null,
      content: (
        <Space direction="vertical" style={{ width: '100%', marginTop: 16 }}>
          <Button 
            block 
            icon={<CopyOutlined />} 
            onClick={async () => {
              try {
                await navigator.clipboard.writeText(content);
                message.success('复制成功');
                Modal.destroyAll();
              } catch (err) {
                message.error('复制失败');
              }
            }}
          >
            复制内容
          </Button>
          {navigator.share && (
            <Button 
              block 
              type="primary" 
              icon={<ShareAltOutlined />}
              onClick={async () => {
                try {
                  await navigator.share({
                    title: 'AI 对话分享',
                    text: content,
                    url: window.location.href
                  });
                  message.success('分享成功');
                  Modal.destroyAll();
                } catch (err) {
                  message.error('分享失败');
                }
              }}
            >
              系统分享
            </Button>
          )}
        </Space>
      ),
      okButtonProps: { style: { display: 'none' } },
      cancelText: '关闭'
    });
  };

  // 处理编辑功能
  const handleEdit = async (message, index) => {
    const newContent = prompt("请输入新的内容:", message.content);
    if (!newContent || newContent === message.content) return;

    try {
      const token = localStorage.getItem('token');
      const cleanToken = token.replace(/['"]+/g, '');

      // 获取新的 AI 回答
      const aiResponse = await fetch(getApiUrl('/api/chat/query'), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${cleanToken}`,
          "x-update-operation": "true",
        },
        body: JSON.stringify({ prompt: newContent }),
      });

      const aiData = await aiResponse.json();
      if (!aiData.ok) {
        throw new Error("获取 AI 回答失败");
      }

      // 更新对话内容
      const newMessages = [...messages];
      newMessages[index] = { ...message, content: newContent };
      if (index < messages.length - 1) {
        newMessages[index + 1] = { role: 'assistant', content: aiData.data };
      }
      setChatContent(newMessages);
    } catch (error) {
      console.error("修改对话失败:", error);
    }
  };

  return (
    <div className="chat-item">
      {messages.map((message, index) => (
        <div key={index}>
          <div className="chat-item-header">
            <img className="chat-item-avatar" src={Avatar} alt="头像" />
            <p className="chat-item-title">{message.role === 'user' ? message.content : 'AI 回复'}</p>
            {message.role === 'user' && (
              <img 
                className="chat-item-edit" 
                src={IconEdit} 
                alt="修改" 
                onClick={() => handleEdit(message, index)}
                style={{ cursor: 'pointer' }}
              />
            )}
          </div>
          <div className="chat-item-content">
            <div className={`chat-message ${message.role}`}>
              {message.role === 'assistant' && (
                <div className="chat-item-content-ai">
                  <span>CHAT A.I+</span>
                  <img src={IconRightBottomArrow} alt="AI" />
                </div>
              )}
              <div className="chat-item-content-inner">
                <ReactMarkdown>{message.content}</ReactMarkdown>
              </div>
              <div className="message-actions">
                <Button 
                  icon={<SoundOutlined />} 
                  onClick={() => handleVoicePlay(message.content)}
                  type={isPlaying ? 'primary' : 'default'}
                />
                <Button icon={<CopyOutlined />} onClick={() => handleCopy(message.content)} />
                <Button icon={<RedoOutlined />} onClick={() => handleRegenerate(message.content, index)} />
                <Button icon={<ShareAltOutlined />} onClick={() => handleShare(message.content)} />
                <Button icon={<MoreOutlined />} />
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

ChatItem.propTypes = {
  chatContent: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.arrayOf(
      PropTypes.shape({
        role: PropTypes.string.isRequired,
        content: PropTypes.string.isRequired,
      })
    )
  ]),
};

ChatItem.defaultProps = {
  chatContent: [],
};
